#version 400 core

#define POSITION	0
#define NORMAL		1
#define COLOR		2
#define TEXCOORD	3
#define FRAG_COLOR	0
#define FRAG_COLOR_AD0 1
#define FRAG_COLOR_AD1 2
#define FRAG_COLOR_AD2 3

uniform sampler2D heightSampler;
uniform sampler2D normalSampler;
uniform float spacing;
uniform ivec2 texRes;

layout(location = FRAG_COLOR) out vec4 COLOR_OUT;

in vec2 fTexcoord;
in float fHeight;
in vec3 fPos;

vec2 smoothCoord( vec2 p )
{
    // [0,1] -> [0.5 -> ]
    p = p*texRes + 0.5;

    vec2 i = floor(p);
    vec2 f = p - i;
    f = f*f*f*(f*(f*6.0-15.0)+10.0);
    p = i + f;

    p = (p - 0.5)/texRes;
    return p;
}

void main()
{
    vec2 s = smoothCoord(fTexcoord);

    vec3 normal = texture(normalSampler, fTexcoord).rgb; 
    //vec3 normal = texture(normalSampler, fTexcoord).rgb; 
    //float height = texture(heightSampler, fTexcoord).r; 

	vec3 lightDir = normalize(vec3(0.0, -1.0, 0.0));

    float LDotN = max(0.0, dot(lightDir, normal));

    //float heightAdjusted = max(0.0, (10.0 + fHeight)*0.015);

    //COLOR_OUT = vec4(heightAdjusted, LDotN*LDotN, 0.0, 1.0);
    COLOR_OUT = vec4(vec3(LDotN), 1.0);
    //COLOR_OUT = vec4(s, 0.0, 1.0);
    //vec3 nn = texture(normalSampler, fTexcoord).rgb; 
    //vec3 nn  = textureOffset(heightSampler, fTexcoord, ivec2(0.0, 0.0)).r;
    //COLOR_OUT = vec4(nn, 1.0);

//    COLOR_OUT = vec4( vec3(0.5) + normal*0.5, 1.0);
    //COLOR_OUT = vec4(vec3(normal.r*0.5f), 1.0);
    //COLOR_OUT = vec4(height*0.5f, normal.r*0.5f,0.0, 1.0);
    //COLOR_OUT = vec4(abs(fHeight)*0.1, 0.0, 0.0, 1.0);
    //COLOR_OUT = vec4(vec3(fHeight*0.1, 0.0, 0.0), 1.0);
	//COLOR_OUT = vec4(1.0, 0.0, 0.0, 1.0);
    //COLOR_OUT = vec4(vec3(1.0f)+normal.rgb*0.5f, 1.0);

    //COLOR_OUT = vec4(1.0, 1.0, 1.0, 1.0);
#if 0 
    float tileSpacing = 75.0;
    ivec2 t = ivec2(fTexcoord.x*tileSpacing, fTexcoord.y*tileSpacing);
    // xor
    if ( ((t.x % 2 == 0) && (t.y % 2 != 0)) ||
         ((t.x % 2 != 0) && (t.y % 2 == 0)) )
        COLOR_OUT = vec4(0.3, 0.25, 0.4, 1.0);
    else 
        COLOR_OUT = vec4(0.3, 0.65, 0.3, 1.0);
#endif 
    //COLOR_OUT = vec4(fTexcoord, 1.0, 1.0);

    //COLOR_OUT = vec4(fTexcoord.x, fTexcoord.y, 0.0, 1.0);

    //COLOR_OUT = vec4(-normal.rgb, 1.0);

    //COLOR_OUT = vec4(1.0, 1.0, 1.0, 1.0);
}
